﻿using System;
using Validity.Contexts;
using Validity.Localization;
using Validity.Rules;

namespace Validity
{
  public static class IsSameAsConstraint
  {
    public static IConditionalValidationContext<TObject, TValue> IsSameAs<TObject, TValue>(this IValidationContext<TObject, TValue> context, TValue value)
      where TValue : class
    {
      return context.IsSameAs(obj => value);
    }

    public static IConditionalValidationContext<TObject, TValue> IsSameAs<TObject, TValue>(this IValidationContext<TObject, TValue> context, Func<TValue> valueRetriever)
      where TValue : class
    {
      Verify.NotNull(valueRetriever);
      return context.IsSameAs(obj => valueRetriever.Invoke());
    }

    public static IConditionalValidationContext<TObject, TValue> IsSameAs<TObject, TValue>(this IValidationContext<TObject, TValue> context, Func<TObject, TValue> valueRetriever)
      where TValue : class
    {
      Verify.NotNull(valueRetriever);

      context.AddRule(new Rule<TObject, TValue>(
        (obj, val) => ReferenceEquals(val, valueRetriever.Invoke(obj)),
        (obj, val) => String.Format(RuleViolations.SameAs, val)
      ));

      return new ConditionalValidationContext<TObject, TValue>(context);
    }
  }
}
